package keeper.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 
 * @author hliang@126.com
 *
 */
public class ScriptWriter {
	private StringBuilder sb;
	public ScriptWriter() {
		initScript();
	}
	public void initScript() {
		sb = new StringBuilder(2046);
		sb.append("/**\n this program referrence the \n XMLHttpRequest Object Pool \n @author legend <legendsky@hotmail.com> \n @link http://www.ugia.cn/?p=85 \n @Copyright www.ugia.cn \n modify by hliang@126.com \n **/ \n");
		sb.append("var Keeper={_objPool:[],_getInstance:function(){for(var $=0;$<this._objPool.length;$++)");
		sb.append("{if(this._objPool[$].readyState==4)this._objPool[$].readyState==0;");
		sb.append("if(this._objPool[$].readyState==0)return this._objPool[$]}this._objPool[this._objPool.length]=this._createObj();");
		sb.append("return this._objPool[this._objPool.length-1]},_createObj:function(){if(window.XMLHttpRequest)");
		sb.append("var A=new XMLHttpRequest();else{var $=['MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];");
		sb.append("for(var B=0;B<$.length;B++){try{A=new ActiveXObject($[B]);break}catch(_){}}}");
		sb.append("if(A.readyState==null){A.readyState=0;A.addEventListener('load',function()");
		sb.append("{A.readyState=4;if(typeof A.onreadystatechange=='function')A.onreadystatechange()},false)}return A},");
		sb.append("_sendReq:function(method,url,data,callback,eventName,encoding)");
		sb.append("{var objXMLHttp=this._getInstance();with(objXMLHttp)");
		sb.append("{try{if(url.indexOf('?')>0)url+='&randnum='+Math.random();");
		sb.append("else url+='?randnum='+Math.random();open(method,url,true);");
		sb.append("var encode='application/x-www-form-urlencoded; charset='+encoding;");
		sb.append("setRequestHeader('Content-Type',encode);send(data);onreadystatechange=function()");
		sb.append("{if(objXMLHttp.readyState==4&&(objXMLHttp.status==200||objXMLHttp.status==304))");
		sb.append("{callback(objXMLHttp);Keeper.addListener(eventName,callback)}}}catch(e){alert(e.description)}}},");
		sb.append("addListener:function(A,_,$){if($==null)$='UTF-8';var B='./keeper?event='+A;_callback=_;");
		sb.append("this._sendReq('GET',B,'',_,A,$)},removeListener:function($){alert('unsupport method')}}");
	}
	public void output(File file) {
		try {
			FileOutputStream fo = new FileOutputStream(file);
			fo.write(sb.toString().getBytes());
			fo.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
